package com.easylinkin.linkappapi.investigation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.investigation.entity.InvestigationType;
import com.easylinkin.linkappapi.investigation.mapper.InvestigationTypeMapper;
import com.easylinkin.linkappapi.investigation.service.InvestigationTaskModelContentService;
import com.easylinkin.linkappapi.investigation.service.InvestigationTypeService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ckx
 * @desc 排查类型
 * @date 2020-04-13
 */
@Service
public class InvestigationTypeServiceImpl extends ServiceImpl<InvestigationTypeMapper, InvestigationType> implements InvestigationTypeService {

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;
    @Resource
    InvestigationTaskModelContentService investigationTaskModelContentService;

    /**
     * 分页查询排查类型
     *
     * @author ckx
     * @date 2020-04-13
     */
    @Override
    public IPage<InvestigationType> getInvestigationTypePage(Page page, InvestigationType investigationType) {
        QueryWrapper<InvestigationType> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(investigationType.getName())) {
            queryWrapper.like("name", investigationType.getName());
        }
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        queryWrapper.orderByDesc("modify_time","create_time");
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 分页查询排查类型
     *
     * @author ckx
     * @date 2020-04-13
     */
    @Override
    public List<InvestigationType> getInvestigationTypeAll() {
        QueryWrapper<InvestigationType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        queryWrapper.orderByDesc("create_time");
        List<InvestigationType> investigationTypeList=baseMapper.selectList(queryWrapper);
        return investigationTypeList;
    }

    /**
     * 新增排查类型
     *
     * @author ckx
     * @date 2020-04-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addInvestigationType(InvestigationType investigationType) {
        //检查效验
        validParamRequired(investigationType);
        validParamFormat(investigationType);
        //获取租户
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        investigationType.setTenantId(linkappUser.getTenantId());
        //检查重复名称
        validRepeat(investigationType);

        investigationType.setCreateTime(new Date());
        investigationType.setCreator(String.valueOf(linkappUser.getId()));
        //保存
        save(investigationType);
        return true;
    }

    /**
     * 修改排查类型
     *
     * @author ckx
     * @date 2020-04-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInvestigationType(InvestigationType investigationType) {
        //检查效验
        validParamRequired(investigationType);
        validParamFormat(investigationType);
        InvestigationType originInvestigationType = getById(investigationType.getId());
        Assert.notNull(originInvestigationType, "原排查类型不存在");
        //获取租户
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        investigationType.setTenantId(linkappUser.getTenantId());
        //检查重复
        validRepeat(investigationType);
        investigationType.setModifyTime(new Date());
        investigationType.setModifier(String.valueOf(linkappUser.getId()));
        //修改
        updateById(investigationType);
        return true;
    }

    /**
     * 批量删除排查类型
     *
     * @author ckx
     * @date 2020-04-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delInvestigationTypeList(List<InvestigationType> investigationTypeList) {
        Assert.notEmpty(investigationTypeList, "参数为空");
        //获取ids集合
        List<Long> ids = investigationTypeList.stream().map(InvestigationType::getId).collect(Collectors.toList());
        int count = investigationTaskModelContentService.countByInvestigationTypeIds(ids);
        if (count > 0) {
            throw new BusinessException("要删除的排查类型已在使用中，不允许删除");
        }
        //批量删除
        removeByIds(ids);
        return true;
    }

    /**
     * 校验重复
     */
    private void validRepeat(InvestigationType investigationType) {
        QueryWrapper<InvestigationType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", investigationType.getName());
        queryWrapper.eq("tenant_id", investigationType.getTenantId());
        List<InvestigationType> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("排查类型名称有重复");
        }
        if (investigationType.getId() == null) {
            throw new BusinessException("排查类型名称已存在");
        }
        if (!investigationType.getId().equals(list.get(0).getId())) {
            throw new BusinessException("排查类型名称已存在");
        }

    }

    /**
     * 校验参数必填
     */
    private void validParamRequired(InvestigationType investigationType) {
        Assert.notNull(investigationType, "参数为空");
        Assert.isTrue(StringUtils.isNotBlank(investigationType.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(InvestigationType investigationType) {
        Assert.isTrue(investigationType.getName() == null || investigationType.getName().length() <= 50, "名称超长");
        Assert.isTrue(investigationType.getDescription() == null || investigationType.getDescription().length() <= 225, "说明超长");
    }
}
